package org.yscz.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.yscz.common.Constants;
import org.yscz.common.enums.UserResponseEnum;
import org.yscz.entity.Role;
import org.yscz.entity.Testee;
import org.yscz.entity.User;
import org.yscz.entity.UserRoleRelation;
import org.yscz.entity.vo.UserVo;
import org.yscz.exception.*;
import org.yscz.mapper.RoleMapper;
import org.yscz.mapper.TesteeMapper;
import org.yscz.mapper.UserMapper;
import org.yscz.mapper.UserRoleRelationMapper;
import org.yscz.mqtt.MqttCustomClient;
import org.yscz.service.UserService;

import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * @author achen
 * @create 2021-08-13 17:48
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleRelationMapper userRoleRelationMapper;

    @Value("${yscz.pictures.upload.userFaceLocation}")
    private String userFaceLocation;

    @Autowired
    private MqttCustomClient mqttCustomClient;

    /**
     * 通过用户名和密码查询用户
     *
     * @param user 用户信息
     * @return user对象
     */
    @Override
    public User login(User user) {

        JSONObject resultObj = new JSONObject();

        //如果传过来空数据
        if ("".equals(user.getPhone().trim()) && "".equals(user.getPassword().trim())) {
            throw new CustomUserException(UserResponseEnum.USERNAME_PASSWORD_NOT_EMPTY);
        }

        //如果用户名为空，给出提示
        if ("".equals(user.getPhone().trim())) {
            throw new CustomUserException(UserResponseEnum.USERNAME_PASSWORD_NOT_EMPTY);
        }

        //如果密码为空，给出提示
        if ("".equals(user.getPassword().trim())) {
            throw new CustomUserException(UserResponseEnum.PASSWORD_NOT_EMPTY);
        }

        //根据用户名和密码查询是否存在此用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", user.getPhone());
        User userDB = userMapper.selectOne(queryWrapper);
        log.info("user:[{}]", userDB);

        //如果userDB为空,说明该用户不存在，给出提示
        if (StringUtils.isEmpty(userDB)) {
            throw new CustomUserException(UserResponseEnum.USER_NOT_EXIST);
        }

        //密码不对给出提示
        if (!userDB.getPassword().equals(user.getPassword())) {
            throw new CustomUserException(UserResponseEnum.PASSWORD_ERROR);
        }

        //账号被禁用
        if (Constants.ACCOUNT_DISABLED_STATUS.equals(userDB.getStatus())) {
            throw new CustomUserException(UserResponseEnum.ACCOUNT_DISABLED_ERROR);
        }
        return userDB;
    }

    @Override
    public UserVo add(UserVo userVo) {
        User user = new User();
        BeanUtils.copyProperties(userVo, user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());

        userMapper.insert(user);

        // 维护用户-角色关联关系
        UserRoleRelation userRoleRelation = new UserRoleRelation();
        userRoleRelation.setUserId(user.getUserId());
        userRoleRelation.setRoleId(userVo.getRoleId());
        userRoleRelationMapper.insert(userRoleRelation);

        return userVo;
    }

    @Override
    public void modify(UserVo userVo) {
        User user = new User();
        BeanUtils.copyProperties(userVo, user);
        user.setUpdateTime(new Date());

        userMapper.updateById(user);

        // 维护用户-角色关联关系
        UserRoleRelation userRoleRelation = new UserRoleRelation();
        userRoleRelation.setRoleId(userVo.getRoleId());

        UpdateWrapper<UserRoleRelation> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", userVo.getUserId());
        userRoleRelationMapper.update(userRoleRelation, updateWrapper);
    }

    @Override
    public void del(Long userId) {
        User user = userMapper.selectById(userId);
        if (null != user) {
            //删除人脸库照片
            String httpImageUrl = user.getImageUrl();
            //f17b6c4a-760a-45bc-bc7d-1a5e02f14182.jpg
            String imageUrl = httpImageUrl.substring(33, httpImageUrl.length());
            //人脸库文件路径
            String fileLocation = userFaceLocation + File.separator + imageUrl;

            File file = new File(fileLocation);
            if (null != file) {
                file.delete();
            }
        }
        userMapper.deleteById(userId);

        //通知算法更新人脸库
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uuid", "1234");
        mqttCustomClient.publish(Constants.UPDATE_FACE_IMAGE_CONTROL, JSONObject.toJSONString(jsonObject));
    }

    @Override
    public IPage<User> listPage(QueryWrapper queryWrapper, IPage<User> page) {
        return userMapper.selectPage(page, queryWrapper);
    }

    @Override
    public List<Role> roleList(QueryWrapper queryWrapper) {
        return roleMapper.selectList(queryWrapper);
    }

    @Override
    public Role getUserRole(Long userId) {
        return roleMapper.querRoleByUserId(userId);
    }

    @Override
    public void resetPwdByUserId(Long userId) {
        User user = new User();
        user.setUpdateTime(new Date());
        user.setPassword("123456");
        userMapper.updateById(user);
    }

    @Override
    public UserVo getUserDetail(Long userId) {
        return userMapper.getUserDetail(userId);
    }
}
